package com.itheima.bos.web.action.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.IUserService;
import com.itheima.bos.web.action.base.BaseAction;
import com.opensymphony.xwork2.ActionContext;

/**
 * 后台员工登录的action
 * @author yanju
 *
 */

@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class UserAction extends BaseAction<User> {

	@Action(value="bos_login",results={@Result(name="success",type="redirect",location="index.html"),
										@Result(name="login",type="redirect",location="login.html")})
	public String bos_login(){
		//基于shiro实现登录
		
		//用户登录的信息都存放在subject中
		Subject subject = SecurityUtils.getSubject();
		
		//键数据封装入token中
		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
		
		try {
			//登录操作
			subject.login(token);
			//登录成功
			return SUCCESS;
		} catch (AuthenticationException e) {
			e.printStackTrace();
			//登录失败
			return LOGIN;
		}
	}
	
	/*
	 * 用户退出的action
	 * 
	 */
	
	@Action(value="user_logout",results={@Result(name="success",type="redirect",location="login.html")})
	public String user_logout(){
		Subject subject = SecurityUtils.getSubject();	
		subject.logout();
		return SUCCESS;
	}
	
	/*
	 * 用户展示的action
	 */
	
	@Autowired
	private IUserService userServiceimpl;
	
	
	
	@Action(value="user_list",results={@Result(name="success",type="json")})
	public String user_list(){
		
		List<User> results=userServiceimpl.findAll();
		ActionContext.getContext().getValueStack().push(results);
		
		return SUCCESS;
	}
	
	
	/**
	 * 用户添加的action
	 * 
	 */
	private String[] roleIds;
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	@Action(value="user_save",results={@Result(name="success",type="redirect",location="/pages/system/userlist.html")})
	public String user_save(){
		
		userServiceimpl.save(model,roleIds);
		return SUCCESS;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
